package com.avic.rong.search.activity;

import android.graphics.Typeface;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.search.adapter.SearchViewHomeReMenRvAdapter;
import com.avic.rong.search.adapter.homePageAdapter.SearchHomePageBuQuanRvAdapter;
import com.avic.rong.search.api.SearchHomePageBuQuanApi;
import com.avic.rong.search.api.SearchHotApi;
import com.avic.rong.search.bean.SearchHotBean;
import com.avic.rong.search.bean.SearchPupopBean;
import com.avic.rong.search.db.User;
import com.avic.rong.search.db.UserDbUtil;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.EditUtils;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.coorchice.library.SuperTextView;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.github.hymanme.tagflowlayout.TagAdapter;
import com.github.hymanme.tagflowlayout.TagFlowLayout;
import com.github.hymanme.tagflowlayout.bean.TagBean;
import com.github.hymanme.tagflowlayout.tags.ColorfulTagView;
import com.github.hymanme.tagflowlayout.tags.DefaultTagView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchHomePageActivity extends BaseActivity implements SearchHomePageBuQuanRvAdapter.SearchHomePageRvListener,
        SearchViewHomeReMenRvAdapter.SearchViewHomeReMenListener, View.OnClickListener {


    public static String NOW_SEARCHSTR = "searchStr";

    @BindView(R.id.edt_search)
    EditText edt_search;

    @BindView(R.id.search_homePage_RelativeLayout)
    RelativeLayout searchHomePageRelativeLayout;
    @BindView(R.id.img_edit_delete)
    ImageView img_edit_delete;
    @BindView(R.id.recycler_list_hot)
    RecyclerView recycler_list_hot;

    //搜索记录组
    @BindView(R.id.ll_record_group)
    LinearLayout ll_record_group;


    @BindView(R.id.search_homePage_DrawerLayout)
    LinearLayout searchHomePageDrawerLayout;

    @BindView(R.id.ll_hot_group)//热门搜索组
            LinearLayout ll_hot_group;
    @BindView(R.id.tag_flow_layout)
    TagFlowLayout tag_flow_layout;

    @BindView(R.id.search_loading)
    LoadingLayout search_loading;

    @BindView(R.id.stv_search_title)//搜索记录标题
            SuperTextView stv_search_title;
    @BindView(R.id.img_arrow)
    ImageView img_arrow;

    @BindView(R.id.recycler_list_buquan)
    RecyclerView recycler_list_buquan;
    @BindView(R.id.ll_buquan_group)
    LinearLayout ll_buquan_group;

    @BindView(R.id.scroll_view)
    NestedScrollView scroll_view;
    @BindView(R.id.ll_group_arrow)
    LinearLayout ll_group_arrow;


    private SearchHomePageBuQuanRvAdapter buQuanRvAdapter;
    private SearchViewHomeReMenRvAdapter reMenRvAdapter;

    private ArrayList<SearchHotBean> searchHotBeans = new ArrayList<>();

    private List<String> buquanList = new ArrayList<>();
    private MyTagAdapter tagAdapter;


    public static String nowSearchStr = ConstantsUtils.EMPTY_STR;
    private SearchHotApi hotApi;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_search_home_page;
    }

    @Override
    protected void initView() {

        edt_search.requestFocus();//光标出现
        //显示软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //如果上面的代码没有弹出软键盘 可以使用下面另一种方式
        //InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        // imm.showSoftInput(editText, 0);

        //热门
        GridLayoutManager manager = new GridLayoutManager(SearchHomePageActivity.this, 2);
        recycler_list_hot.setLayoutManager(manager);
        reMenRvAdapter = new SearchViewHomeReMenRvAdapter(SearchHomePageActivity.this);
        reMenRvAdapter.setListener(this);

        //联想词
        buQuanRvAdapter = new SearchHomePageBuQuanRvAdapter(SearchHomePageActivity.this);
        recycler_list_buquan.setLayoutManager(new LinearLayoutManager(SearchHomePageActivity.this));
        DividerItemDecoration divider = new DividerItemDecoration(SearchHomePageActivity.this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(SearchHomePageActivity.this, R.drawable.divider_05_pix));
        recycler_list_buquan.addItemDecoration(divider);
        recycler_list_buquan.setAdapter(buQuanRvAdapter);
        buQuanRvAdapter.setSearchHomePageRvListener(this);

        tagAdapter = new MyTagAdapter();
        tag_flow_layout.setTagAdapter(tagAdapter);
        tag_flow_layout.setCanScroll(false);
        tag_flow_layout.setItemModel(TagFlowLayout.ITEM_MODEL_CLICK);


        //获取热搜
        hotApi = new SearchHotApi(SearchHomePageActivity.this, delCartListener);
        hotApi.setCache(false);
        search_loading.setStatus(LoadingLayout.LOADING);
        search_loading.showReturnButton();
        HttpManager.getInstance().doHttpDeal(hotApi);
        search_loading.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(hotApi);
                search_loading.setStatus(LoadingLayout.LOADING);
            }

            @Override
            public void onReturn(View v) {
                finish();
            }
        });


        initListener();
        historyDbData();


    }


    //获取搜索历史数据
    private void historyDbData() {
        List<User> users = UserDbUtil.getInstance().queryUserAll();
        if (users.size() == 0) {
            ll_record_group.setVisibility(View.GONE);
        } else {
            ll_record_group.setVisibility(View.VISIBLE);

            List<TagBean> tagBeans = new ArrayList<>();
            for (User user : users) {
                tagBeans.add(new TagBean(user.getId(), user.getText()));
            }
            tagAdapter.addAllTags(tagBeans);
        }
        tag_flow_layout.setCurrentLineInterface(new TagFlowLayout.CurrentLineInterface() {
            @Override
            public void lines(int size) {
                if (size > 2) {
                    ll_group_arrow.setOnClickListener(SearchHomePageActivity.this);
                    img_arrow.setVisibility(View.VISIBLE);
                } else {
                    img_arrow.setVisibility(View.INVISIBLE);
                }
            }
        });

    }


    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.ll_group_arrow) {//搜索箭头
            tag_flow_layout.moreClickControl(img_arrow);
        }
    }

    //more箭头点击
    @OnClick({R.id.tv_cancel, R.id.img_delete, R.id.img_edit_delete})
    public void moreControl(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.tv_cancel://取消
                this.finish();
                EditUtils.hideSoftKeyboard(SearchHomePageActivity.this, edt_search);
                break;
            case R.id.img_delete://删除
                DialogCustom.showDoubleDialog(this, "提示", "确定要清空搜索记录吗?", "取消", "确认", new DialogCustom.CustomDialogDouble() {
                    @Override
                    public void rightButtonClicked() {
                        UserDbUtil.getInstance().deleteAll();
                        historyDbData();
                    }

                    @Override
                    public void leftButtonClicked() {

                    }
                });
                break;
            case R.id.img_edit_delete://编辑右上删除
                edt_search.setText("");
                buquanList.clear();
                scroll_view.setVisibility(View.VISIBLE);
                ll_buquan_group.setVisibility(View.GONE);

                break;
        }
    }


    //获取热搜数据监听
    HttpOnNextListener delCartListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(subjects.getCode())) {
                Logger.e("cjx", "热搜：" + subjects.getMsg());
                search_loading.setStatus(LoadingLayout.ERROR);
                return;
            }
            search_loading.setStatus(LoadingLayout.SUCCESS);
            searchHotBeans.clear();
            searchHotBeans.addAll((ArrayList<SearchHotBean>) subjects.getData());
            recycler_list_hot.setAdapter(reMenRvAdapter);
            reMenRvAdapter.setBeans(searchHotBeans);
        }


        @Override
        public void onError(final Throwable e) {
            search_loading.setStatus(LoadingLayout.ERROR);
            Logger.e("cjx", "热搜数据" + e.getMessage());
        }
    };


    //搜索补全点击事件
    @Override
    public void setCurrentText(String searchStr) {
        Log.e("cjx", "SearchHomePageBuQuanListener-------nowSearchStr" + searchStr);
        nowSearchStr = searchStr;
        skipActivity(searchStr);
        img_edit_delete.setVisibility(View.GONE);
        EditUtils.showORhideSoftKeyboard(SearchHomePageActivity.this);//关闭软键盘
        finish();
    }

    //热门搜索点击事件
    @Override
    public void remenGoResult(String searchStr) {
        nowSearchStr = searchStr;
        skipActivity(searchStr);
        System.out.println("----uuu------" + searchStr);
//        nowSearchStr = searchHotBeans.get(index).getWord();
//        Log.e("cjx", "nowSearchText1:" + searchHotBeans.get(index).getWord());
//        Intent intent = new Intent(context, SearchResaultActivity.class);
//
//        intent.putExtra(SearchHomePageActivity.NOW_SEARCHSTR, searchHotBeans.get(index).getWord());
//        context.startActivity(intent);
//        context.finish();
    }


    private void skipActivity(String searchStr) {
        UserDbUtil.getInstance().saveUserMax20(new User(searchStr));
        startActivity(SearchResaultActivity.getIntent(context, searchStr));
//        startActivity(SearchMainActivity.getIntent(context));
        finish();
    }


    //获取搜索补全数据
    private void initBuQuanData(String searchStr) {
        SearchHomePageBuQuanApi goodsSortApi = new SearchHomePageBuQuanApi(this, buQuanListener, searchStr);
        goodsSortApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(goodsSortApi);
    }

    //获取搜索补全数据监听
    HttpOnNextListener buQuanListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals("200")) {
                Log.e("cjx", "图书属性:" + subjects.getData());
                return;
            }
            buquanList.clear();
            if (subjects.getData() != null && !ConstantsUtils.EMPTY_STR.equals(subjects.getData())) {
                SearchPupopBean bean = (SearchPupopBean) subjects.getData();
                Logger.i("cjx", "bean.getKeywords:" + bean.getKeywords() + "------------nowSearchStr:" + nowSearchStr);
                if (bean.getKeywords().equals(nowSearchStr)) {
                    buquanList.addAll(bean.getRelateList());
                    if (buquanList != null) {
                        scroll_view.setVisibility(View.GONE);
//                        ll_hot_group.setVisibility(View.GONE);
//                        ll_record_group.setVisibility(View.GONE);
                        ll_buquan_group.setVisibility(View.VISIBLE);
                        buQuanRvAdapter.setDataList(buquanList);
                    } else {
                        return;
                    }
                } else {
                    return;
                }
            } else {
                ll_hot_group.setVisibility(View.VISIBLE);
                ll_buquan_group.setVisibility(View.GONE);
                return;
            }
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", "bz拿到数据" + e.getMessage());
        }
    };

    private void initListener() {
        edt_search.addTextChangedListener(watcher);
        edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    EditUtils.hideSoftKeyboard(SearchHomePageActivity.this, edt_search);
                    nowSearchStr = edt_search.getText().toString();
                    edt_search.setText(nowSearchStr);
                    skipActivity(nowSearchStr);
                    return true;
                }
                return false;
            }
        });
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String currentString = s.toString();
            Log.e(TAG, "--------afterTextChanged: " + currentString);
            if (!TextUtils.isEmpty(currentString)) {
                img_edit_delete.setVisibility(View.VISIBLE);
                nowSearchStr = currentString;
                initBuQuanData(nowSearchStr);
            }
            if (currentString.length() == 0) {
                ll_hot_group.setVisibility(View.VISIBLE);
                ll_buquan_group.setVisibility(View.GONE);
                img_edit_delete.setVisibility(View.GONE);
                buquanList.clear();
            }
        }
    };


    class MyTagAdapter extends TagAdapter<TagBean> {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DefaultTagView textView = new ColorfulTagView(SearchHomePageActivity.this);
            TagBean tagBean = (TagBean) getItem(position);
            textView.setText(tagBean.getName());
            textView.setTextColor(ContextCompat.getColor(SearchHomePageActivity.this, R.color.color_c2c2c2));
            textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            textView.setTextSize(13);
            textView.setSingleLine(true);
            textView.setLines(1);
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setOnClickListener(new TagOnClickListener(tagBean));
            return textView;
        }
    }

    class TagOnClickListener implements View.OnClickListener {

        TagBean tagBean;

        public TagOnClickListener(TagBean tagBean) {
            this.tagBean = tagBean;
        }

        @Override
        public void onClick(View v) { //历史记录点击事件跳转
            skipActivity(tagBean.getName());
        }
    }


    @Override
    protected void onDestroy() {
        EditUtils.hideSoftKeyboard(SearchHomePageActivity.this, edt_search);
        super.onDestroy();
        //关闭软键盘

    }


    @Override
    protected void addListener() {
    }


}
